import Vue from 'vue'
import axios from 'axios'
import {
  baseURL,
  contentType,
  debounce,
  invalidCode,
  noPermissionCode,
  requestTimeout,
  successCode,
  requestError,
  tokenName,
  loginInterception
} from '@/config'
import store from '@/store'
import qs from 'qs'
import router from '@/router'
import { isArray } from '@/utils/validate'
// import { Encrypt, Decrypt } from '@/utils/decrypt'
// import whiteList from '@/utils/whiteList'

let loadingInstance
const handleCode = (code, msg) => {
  switch (code) {
    case invalidCode:
      // 掉接口再放开
      Vue.prototype.$baseMessage.error(`该账号在其他设备登录或登录超时,请重新登录!`, 'error')
      store.dispatch('user/resetAccessToken').catch(() => {})
      if (loginInterception) {
        location.reload()
      }
      break
    case requestError:
      Vue.prototype.$baseMessage.error(msg || `请求服务报错，请联系开发人员`, 'error')
      break
    case noPermissionCode:
      router.push({ path: '/401' }).catch(() => {})
      break
    default:
      Vue.prototype.$baseMessage.error(msg || `服务接口${code}异常`, 'error')
      break
  }
}
const instance = axios.create({
  baseURL,
  timeout: requestTimeout,
  headers: {
    'Content-Type': contentType,
    'X-Frame-Options': 'SAMEORIGIN'
  }
})
instance.interceptors.request.use(
  (config) => {
    if (store.getters['user/accessToken']) {
      config.headers[tokenName] = store.getters['user/accessToken']
    }
    if (
      config.data &&
      config.headers['Content-Type'] ===
        'application/x-www-form-urlencoded;charset=UTF-8'
    ) {
      config.data = qs.stringify(config.data)
    }
    if (debounce.some((item) => config.url.includes(item))) { loadingInstance = Vue.prototype.$baseLoading() }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response) => {
    if (loadingInstance) loadingInstance.close()
    if (response.data instanceof Blob) {
      return response.data
    }
    if (response.data instanceof ArrayBuffer) {
      return response.data
    }
    const { data, config } = response
    // 对数据进行解密
    // const { code, msg } = whiteList.indexOf(config.url) !== -1 ? data : (typeof data === 'object' ? data : JSON.parse(Decrypt(data)))
    const { code, msg } = data
    // 操作正常Code数组
    const codeVerificationArray = isArray(successCode)
      ? [...successCode]
      : [...[successCode]]
    // 是否操作正常
    // if (!(response instanceof Blob)) return data
    if (codeVerificationArray.includes(code) || typeof response.data === 'string') {
      // return whiteList.indexOf(config.url) !== -1 ? data : (typeof data === 'object' ? data : JSON.parse(Decrypt(data)))
      return data
    } else {
      handleCode(code, msg)
      return Promise.reject(
        'base-web请求异常拦截:' +
          JSON.stringify({ url: config.url, code, msg }) || 'Error'
      )
    }
  },
  (error) => {
    if (loadingInstance) loadingInstance.close()
    const { response, message } = error
    console.log(response, message)
    if (error.response && error.response.data) {
      const { data } = response
      handleCode(data.code, data.msg || message)
      return Promise.reject(error)
    } else {
      let { message } = error
      if (message === 'Network Error') {
        message = '连接服务网络异常'
      }
      if (message.includes('timeout')) {
        message = '请求服务接口超时'
      }
      if (message.includes('Request failed with status code')) {
        const code = message.substr(message.length - 3)
        message = '服务接口' + code + '异常'
      }
      Vue.prototype.$baseMessage.error(message || `后端接口未知异常`, 'error')
      return Promise.reject(error)
    }
  }
)

export default instance
